import { configs, settings } from './localStorage'

export default function (options) {
    
    let _url = null;
    let currentConfig = configs.getConfig();
    if (currentConfig.isApp && plus.networkinfo.getCurrentType() === plus.networkinfo.CONNECTION_NONE) {
        app.mui.toast('<a href="javascript:void(0);" style="text-decoration: underline;color: #FFF;" onclick="window.location.reload();">亲~网络连接不上，请检测网络。点此刷新重试</a>', { duration: '8000', type: 'div' });
        return;
    }
    if (typeof (options) === "string") {
        _url = options;
    } else if (typeof (options) !== "object" || !options.url) {
        mui.alert("Ajax 参数错误！");
        return;
    } else {
        _url = options.url;
        delete options.url;
    }

    var _default = {
        type: "POST",
        dataType: "json",
        headers: { 'Content-Type': 'application/json' },
        processData: true, //是否自动处理data数据
        async: true,
        timeout: 20000,
        auth: false, //是否验证当前API接口的登录权限
        authFailCallbackFun: null, // 验证失败的回调函数
        showLoading: true //是否显示加载
    };
    var _options = mui.extend(true, {}, _default, options);
    if (!_options.data) {
        _options.data = {};
    }
    if (_options.type.toUpperCase() === 'GET') {
        _options.headers = { "Content-Type": "application/x-www-form-urlencoded" };
        _options.data = _options.data || {};
    }
    if (!_url.match(/^(?:http|ftp|https):\/\//) && _url.lastIndexOf(".json") == -1) {
        //如果传的url含有 http://说明是个绝对路径，就不用拼了
        _url = settings.getSettings().webapiDomain + _url;
    }
    if (_default.processData && typeof (_options.data) === "object" && _options.type.toUpperCase() === 'POST') {
        //POST DATA处理代码
    }
    if (_options.auth === true && !app.globalService.isLogin()) {
        if (typeof (_options.authFailCallbackFun) === "function") {
            _options.authFailCallbackFun();
        }
        return;
    }
    _options.success = function (res, textStatus) {
        if (_options.showLoading === true) {
            mui('body').progressbar().hide();
        }
        if (res.code == 0) {
            mui.toast(res.data);
            if (res.data === 'Authentication Error') {
                localStorage.setItem('$needloginpage', JSON.stringify({id: '_', url: window.location.href}));
                window.toPage({
                    "id": 'login',
                    "url": 'login.html'
                })
            }
            return;
        }
        if (typeof (options.success) === "function") {
            options.success(res.data);
        }
    };
    _options.complete = function (data, textStatus) {
        if (_options.showLoading === true) {
        }
        if (typeof (options.complete) === "function") {
            options.complete(data, textStatus);
        }
    };
    _options.error = function (xhr, error) {
        if (_options.showLoading === true) {
            mui('body').progressbar().hide();
        }
        if (typeof (options.error) === "function") {
            options.error(xhr, error);
        } else if (xhr.response) {

        } else {
            mui.toast('<a href="javascript:void(0);" style="text-decoration: underline;color: #FFF;" onclick="window.location.reload();">亲~服务出错了。点此刷新重试</a>', { duration: 8000, type: 'div' });
        }
    };
    _options.beforeSend = function (xhr) {
        let _token = settings.getSettings().token;

        if (_token) {
            xhr.setRequestHeader("Authorization", 'Bearer ' + _token);
        }
        if (_options.showLoading === true) {
            
        }
        if (typeof (options.beforeSend) === "function") {
            options.beforeSend(xhr);
        }
    };

    mui.ajax(_url, _options);
};

































